from django.db import models
from django import forms
from django.contrib.auth.models import User
from django.conf import settings

from tags.templatetags.sanitize import sanitize
from apps.additions import AllowAdditions
from apps.course.models import Course,CourseForm
from apps.course.functions import course_reverse
from apps.feeds import FeedItem, FeedItems

import datetime
import logging
import calendar

logger = logging.getLogger('pet.apps.news.models')
   
# Create your models here.
class NewsCalendar(calendar.HTMLCalendar):
	def formatday(self, day, weekday):
		"""
		  Return a day as a table cell.
		"""
		if day == 0:
			return '<td class="noday">&nbsp;</td>' # day outside month
		else:
			return '<td class="%s"><a href="%s">%d</a></td>' % (self.cssclasses[weekday], weekday, day)
class Announcement(FeedItem):
	title = models.CharField(max_length=255)
	date = models.DateTimeField(auto_now_add = True)
	course = models.CharField(max_length=255)
	description = models.TextField(blank = True, null = True)
	def __unicode__(self):
		return "%s - %s" % (self.date, self.title)
	def save(self, *args, **kwargs):
		self.title = sanitize(self.title)
		self.description = sanitize(self.description)
		super(Announcement,self).save(*args,**kwargs)
	def get_appearance_date(self):
		return self.date
	def get_link(self,course):
		return course_reverse('apps.news.views.index',course)
	def get_title(self):
		return self.title
	def get_description(self):
		return self.description
AllowAdditions(Announcement)
FeedItems.register_item('News',Announcement)

class AnnouncementForm(CourseForm):
	def __init__(self, *args, **kwargs):
		super(AnnouncementForm,self).__init__(*args, **kwargs)
		self.fields['title'].widget.attrs['size'] = 65
		#self.fields['description'].widget.attrs['cols'] = 55
		#self.fields['description'].widget.attrs['rows'] = 30
	class Meta:
		model = Announcement
		exclude = ['date']

def GetAnnouncements(course,num_to_show=0):
	AnnouncementsToShow = []
	TheCourse = Course.find_or_404(course)
	for item in Announcement.objects.order_by('-date'):
		if TheCourse.course_id in item.course.split(','):
			AnnouncementsToShow.append(item)
	#logger.debug("AnnouncementsFound - %s",AnnouncementsToShow)
	#import traceback
	#traceback.print_stack()
	if (num_to_show > 0):
		AnnouncementsToShow = AnnouncementsToShow[:num_to_show]
		
	return AnnouncementsToShow

class Event(FeedItem):
	title = models.CharField(max_length=255)
	appearance_date = models.DateTimeField(auto_now_add = True)
	course = models.CharField(max_length=255)
	date = models.DateField()
	description = models.TextField(blank = True, null = True)
	calendar_only = models.BooleanField("Calendar-Only",default=False,help_text="If true, this event will show up on the calendar but not in the event listing")
	def __unicode__(self):
		return "%s - %s" % (self.date, self.title)
	def save(self, *args, **kwargs):
		self.title = sanitize(self.title)
		self.description = sanitize(self.description)
		super(Event,self).save(*args,**kwargs)
	def get_appearance_date(self):
		return self.appearance_date
	def get_link(self,course):
		return course_reverse('apps.news.views.index',course)
	def get_title(self):
		return self.title
	def get_description(self):
		return self.description
AllowAdditions(Event)
FeedItems.register_item('News',Event)

class EventForm(CourseForm):
	def __init__(self, *args, **kwargs):
		super(EventForm,self).__init__(*args, **kwargs)
		self.fields['title'].widget.attrs['size'] = 60
		#self.fields['description'].widget.attrs['cols'] = 55
		#self.fields['description'].widget.attrs['rows'] = 30
	class Meta:
		model = Event
		exclude = ['appearance_date']
	
def GetEvents(course,num_to_show=0):
	TheCourse = Course.find_or_404(course)
	EventsToShow = Event.objects.filter(course__contains=TheCourse.course_id,calendar_only=False).order_by('-date').exclude(date__lt = datetime.date.today())
	if (num_to_show > 0):
		EventsToShow = EventsToShow[:num_to_show]
	return EventsToShow

def GetPastEvents(course,num_to_show=0):
	TheCourse = Course.find_or_404(course)
	EventsToShow = Event.objects.filter(course__contains=TheCourse.course_id,calendar_only=False).order_by('-date').exclude(date__gte = datetime.date.today())
	if (num_to_show > 0):
		EventsToShow = EventsToShow[:num_to_show]
	return EventsToShow